package toman;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * User: zslajchrt
 * Date: 2.5.11
 * Time: 14:21
 */
public class QueryEngineSelectorImpl implements QueryEngineSelector {

    private final List<QueryEngine> engines;

    public QueryEngineSelectorImpl() {
        this(Collections.<QueryEngine>emptyList());
    }

    public QueryEngineSelectorImpl(List<QueryEngine> engines) {
        this.engines = new ArrayList<QueryEngine>(engines);
    }

    public QueryEngine selectEngineForFindInitObject(TOMan toman, Class<?> toClass, Object toId) {
        for (QueryEngine engine : engines) {
            if (engine.canFindInitObject(toman, toClass, toId)) {
                return engine;
            }
        }
        throw new NoQueryEngineFoundException(toId);
    }

    public QueryEngine selectEngineForCreateQueryForUpdate(TOMan toman, Object to) {
        for (QueryEngine engine : engines) {
            if (engine.canCreateQueryForUpdate(toman, to)) {
                return engine;
            }
        }
        throw new NoQueryEngineFoundException(to);
    }

    public QueryEngine selectEngineForCreateQuery(TOMan toman, Class<?> toClass, Object queryDefinition) {
        for (QueryEngine engine : engines) {
            if (engine.canCreateQuery(toman, toClass, queryDefinition)) {
                return engine;
            }
        }
        throw new NoQueryEngineFoundException(queryDefinition);
    }

    public void addEngine(int position, QueryEngine engine) {
        engines.add(position, engine);
    }

    public void addEngine(QueryEngine engine) {
        engines.add(engine);
    }
}
